import * as THREE from '../build/three.module.js';
import { addSimpleLabel } from './Label3D.js';
import {AddObjectCommand, RemoveObjectCommand} from '../js/commands/Commands.js'

function Toolbar(editor, assetManager){
    var signals = editor.signals;
    var isPlaying = false;
    $('#toolbar').w2toolbar({
        name: 'toolbar',
        items: [
            { type: 'menu', id: 'item2', text: 'Application', icon: 'fa fa-heart',
                items: [
                    { id: 'open', text: 'OpenDir', icon: 'fa fa-star', expanded: true,},
                    { id: 'id4', text: 'save', icon: 'fa fa-star', expanded: true,},
                    { id: 'id5', text: 'load', icon: 'fa fa-star', expanded: true,},
                    { id: 'id6', text: 'Import', icon: 'fa fa-star', expanded: true,},
                ]
            },

            { type: 'break' },
            { type: 'menu', id: 'item4', text: 'Add', icon: 'fa fa-star',
                items: [
                    { id: 'id1', text: 'Cube', icon: 'fa fa-star', expanded: true,},
                    { id: 'id2', text: 'Cylinder', icon: 'fa fa-star', expanded: true,},
                    { id: 'id3', text: 'Sphere', icon: 'fa fa-star', expanded: true,},
                    { id: 'id4', text: 'orthographicCamera', icon: 'fa fa-star', expanded: true,},
                    { id: 'id5', text: 'perspectiveCamera', icon: 'fa fa-star', expanded: true,},
                    { id: 'id6', text: 'Label3D', icon: 'fa fa-star', expanded: true,},
                ]
            },
            { type: 'menu', id:'item5', text:'Edit', icon:'fa fa-star',
                items: [
                    { id: 'menu/Edit/delete', text:'Delete', icon:'fa fa-star', expanded: true,},
                ]
            },
            { type: 'button', id:'menu/play', text:'Play/Stop', icon:'fa fa-star'},
        ],
        onClick(event) {
            // console.log(event)
            // if(event.item != null)
            // {
            // 	console.log('Selected:',event.item.id);
            // }
            if (event.subItem == null) return;
            console.log(event.subItem)
            // event.done(function () {
            //     console.log('Selected:', event.item.selected);
            // });

            if(event.subItem.text == "Cube")
            {
                addCube();
            }
            else if(event.subItem.text == "Label3D")
            {
                addLabel3D();
            }
            else if(event.subItem.text == "Sphere")
            {
                addSphere();
            }
            else if(event.subItem.text == "Cylinder")
            {
                addCylinder();
            }
            else if (event.subItem.text === 'orthographicCamera')
            {
                var aspect = editor.camera.aspect;
                var camera = new THREE.OrthographicCamera(-aspect, aspect);
                camera.name = 'OrthographicCamera';
                editor.execute(new AddObjectCommand(editor, camera));
            }
            else if (event.subItem.text === 'perspectiveCamera')
            {
                var camera = new THREE.PerspectiveCamera();
                camera.name = 'PerspectiveCamera';
                editor.execute(new AddObjectCommand(editor, camera));
            }
            else if(event.subItem.text == "save")
            {
                saveToServer();
            }
            else if(event.subItem.text == "load")
            {
                loadFromServer();
            }
            else if (event.subItem.text == "OpenDir")
            {
                assetManager.openFolder();
            }
            else if (event.subItem.text == 'Import')
            {
                editor.loader.import();
            }
            else if (event.subItem.text === 'Delete'){
                var object = editor.selected;
                if (object !== null && object.parent !== null) {
                    editor.execute(new RemoveObjectCommand(editor, object));
                }
            }
            else if (event.subItem.text === 'Play/Stop'){
                if (isPlaying === false){
                    isPlaying = true;
                    signals.startPlay.dispatch();
                }
                else {
                    isPlaying = false;
                    signals.stopPlay.dispatch();
                }
            }
        }
    });

    function addCube(pos,color)
    {
        const geometry = new THREE.BoxGeometry( 200, 200, 200 );
        const material = new THREE.MeshBasicMaterial({color:0xffc0cb});//.MeshLambertMaterial( { map: texture, transparent: true } );
        var mesh = new THREE.Mesh( geometry, material );
        mesh.typename = "cube";
        editor.execute(new AddObjectCommand(editor, mesh))
    }

    function addLabel3D()
    {
        var mesh = addSimpleLabel();
        mesh.typename = "label3d";
        editor.execute(new AddObjectCommand(editor, mesh));
    }

    function addSphere(pos,color)
    {
        //const texture = new THREE.TextureLoader().load( 'textures/crate.gif', render );
        //texture.anisotropy = renderer.capabilities.getMaxAnisotropy();

        const geometry = new THREE.SphereGeometry( 100, 100, 100 );
        const material = new THREE.MeshBasicMaterial({color:0xffc0cb});//new THREE.MeshLambertMaterial( { map: texture, transparent: true } );
        var mesh = new THREE.Mesh( geometry, material );
        mesh.typename = "sphere";
        editor.execute(new AddObjectCommand(editor, mesh))
    }

    function addCylinder(pos,color)
    {
        //const texture = new THREE.TextureLoader().load( 'textures/crate.gif', render );
        //texture.anisotropy = renderer.capabilities.getMaxAnisotropy();

        const geometry = new THREE.CylinderGeometry( 100, 100, 200, 32);
        const material = new THREE.MeshBasicMaterial({color:0xffc0cb});//new THREE.MeshLambertMaterial( { map: texture, transparent: true } );
        var mesh = new THREE.Mesh( geometry, material );
        mesh.typename = "cylinder";
        editor.execute(new AddObjectCommand(editor, mesh))
    }

    function changeColor(color)
    {
        //console.log(curObj.material.color);
        //console.log(color);
        if(curObj!=null)
        {
            curObj.material.color.setHex(color);
            render();
        }
    }
    function onMouseClick( event ) {


        //通过鼠标点击的位置计算出raycaster所需要的点的位置，以屏幕中心为原点，值的范围为-1到1.
        var con = document.getElementById("container")
        mouse.x = ( event.clientX / con.width ) * 2 - 1;
        mouse.y = - ( event.clientY / con.height ) * 2 + 1;

        // 通过鼠标点的位置和当前相机的矩阵计算出raycaster
        raycaster.setFromCamera( mouse, currentCamera );

        // 获取raycaster直线和所有模型相交的数组集合
        var intersects = raycaster.intersectObjects( scene.children );

        //console.log(intersects);
        if(intersects.length>0){

            //intersects[i].object.material.color.set('#ff0000');
            curObj = intersects[0].object;
            control.attach(curObj);

            //set property panel
            $("#posx").val(curObj.position.x)
            $("#posy").val(curObj.position.y)
            $("#posz").val(curObj.position.z)
            $('#color').val(curObj.material.color.getHexString())
        }

        render();

    }

    function saveToServer()
    {
        var jsonobj = [];
        for(var i=0;i<editor.scene.children.length;i++){
            var obj = editor.scene.children[i];
            if(obj.isMesh){
                console.log(obj);
                var meshattr = {type:obj.typename,position:obj.position,color:obj.material.color.getHexString()};
                jsonobj.push(meshattr);
            }
        }
        var str = JSON.stringify(jsonobj);
        console.log(str);

        var xhr = new XMLHttpRequest();
        var url = "/upjson";
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // var json = JSON.parse(xhr.responseText);
                console.log(xhr.responseText);//json.email + ", " + json.password);
            }
        };
        var data = str;//JSON.stringify(editor.toJSON());//JSON.stringify({"email": "hey@mail.com", "password": "101010"});
        //console.log(data);
        xhr.setRequestHeader('Content-Type', ' application/json')
        xhr.send(data);
    }

    function loadFromServer()
    {
        //var str ='[{"type":"cube","position":{"x":450.7144212343155,"y":0,"z":0}},{"type":"cube","position":{"x":-513.8124006551424,"y":0,"z":0}},{"type":"sphere","position":{"x":-79.31718486007924,"y":0,"z":-503.1768780327533}},{"type":"cylinder","position":{"x":-15.695806346158463,"y":0,"z":312.16455099903146}}]';

        var xhr = new XMLHttpRequest();
        var url = "/getjson";
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var txt = xhr.responseText.replaceAll("'","\"");
                txt = txt.replaceAll("True","true");
                txt = txt.replaceAll("False","false");
                //var json = JSON.parse(txt);
                //console.log(json);//json.email + ", " + json.password);
                //editor.fromJSON( json );
                var objs = JSON.parse(txt);
                console.log(objs);
                for(var i=0;i<objs.length;i++)
                {
                    var obj = objs[i];
                    if(obj.type == "cube")
                        addCube(obj.position,obj.color);
                    else if(obj.type == "cylinder")
                        addCylinder(obj.position,obj.color);
                    else if(obj.type == "sphere")
                        addSphere(obj.position,obj.color);
                }
            }
        };
        xhr.send();


    }
    function save()
    {
        var xhr = new XMLHttpRequest();
        var url = "/upjson";
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // var json = JSON.parse(xhr.responseText);
                console.log(xhr.responseText);//json.email + ", " + json.password);
            }
        };
        var data = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
        //console.log(data);
        xhr.setRequestHeader('Content-Type', ' application/json')
        xhr.send(data);
    }
}

export {Toolbar}